package jxl.utils;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;

/**
 * 描述:
 *
 * @Author: ZimH
 * @Mobile: 182-5958-1506
 * @CreateDate: 2019/9/25 14:57
 * @Version: 1.0
 */
public class HttpsUtil {
    /**
     * 获取不安全的HttpsConnection
     * 关闭证书验证，可以和任何https站点建立连接
     * @param url
     * @return
     * @throws IOException
     */
    public static HttpsURLConnection getMyHttpsURLConnection(URL url) throws IOException
    {
        HttpsURLConnection rs = null;

        try {
            rs = (HttpsURLConnection)url.openConnection();
            TrustManager[] trustManagers = {new MyX509TrustManager()};
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustManagers, new SecureRandom());
            rs.setSSLSocketFactory(sslContext.getSocketFactory());
            rs.setHostnameVerifier(new MyHostnameVerifier());
        }
        catch(Exception e)
        {
            throw new IOException(e);
        }

        return rs;
    }

    public static SSLSocketFactory getSSLSocketFactory() throws KeyManagementException, NoSuchProviderException, NoSuchAlgorithmException {
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        return sslContext.getSocketFactory();
    }
}
